/*
 * Unidata Platform
 * Copyright (c) 2013-2020, UNIDATA LLC, All rights reserved.
 *
 * Commercial License
 * This version of Unidata Platform is licensed commercially and is the appropriate option for the vast majority of use cases.
 *
 * Please see the Unidata Licensing page at: https://unidata-platform.com/license/
 * For clarification or additional options, please contact: info@unidata-platform.com
 * -------
 * Disclaimer:
 * -------
 * THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND
 * REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE
 * IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY,
 * FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE AND
 * THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING.
 */
package org.unidata.mdm.data.service.segments.records.merge;

import java.util.UUID;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.unidata.mdm.data.context.MergeRequestContext;
import org.unidata.mdm.data.module.DataModule;
import org.unidata.mdm.data.service.FavoriteEtalonsService;
import org.unidata.mdm.system.type.pipeline.Point;
import org.unidata.mdm.system.type.pipeline.Start;
import org.unidata.mdm.system.type.runtime.MeasurementPoint;

/**
 * @author Alexey Tsarapkin
 */
@Component(RecordMergeFavoritesExecutor.SEGMENT_ID)
public class RecordMergeFavoritesExecutor extends Point<MergeRequestContext> {
    /**
     * This segment ID.
     */
    public static final String SEGMENT_ID = DataModule.MODULE_ID + "[RECORD_MERGE_FAVORITES]";
    /**
     * Localized message code.
     */
    public static final String SEGMENT_DESCRIPTION = DataModule.MODULE_ID + ".record.merge.favorites.description";

    @Autowired
    private FavoriteEtalonsService favoriteEtalonsService;

    /**
     * Constructor.
     */
    public RecordMergeFavoritesExecutor() {
        super(SEGMENT_ID, SEGMENT_DESCRIPTION);
    }
    /**
     * {@inheritDoc}
     */
    @Override
    public void point(MergeRequestContext mergeRequestContext) {
        MeasurementPoint.start();
        try {
            if (CollectionUtils.isNotEmpty(mergeRequestContext.duplicateKeys())) {
                mergeRequestContext.duplicateKeys().forEach(k -> favoriteEtalonsService.remove(UUID.fromString(k.getEtalonKey().getId())));
            }
        } finally {
            MeasurementPoint.stop();
        }
    }
    /**
     * {@inheritDoc}
     */
    @Override
    public boolean supports(Start<?, ?> start) {
        return MergeRequestContext.class.isAssignableFrom(start.getInputTypeClass());
    }
}
